package cn.regexp.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.regexp.domain.ShopGoods;
import cn.regexp.domain.ShopGoodsAttr;
import cn.regexp.domain.ShopGoodsImage;
import cn.regexp.mapper.GoodsAttrMapper;
import cn.regexp.mapper.GoodsImageMapper;
import cn.regexp.mapper.GoodsMapper;
import cn.regexp.query.GoodsQuery;
import cn.regexp.service.IGoodsService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;


@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, ShopGoods> implements IGoodsService {
    @Autowired
    private GoodsImageMapper goodsImageMapper;
    @Autowired
    private GoodsAttrMapper goodsAttrMapper;

    @Override
    public IPage<ShopGoods> queryGoods(GoodsQuery qo) {
        IPage<ShopGoods> shopGoodsPage = new Page<>(qo.getPageNum(), qo.getPageSize());
        QueryWrapper<ShopGoods> wrapper = new QueryWrapper<>();
        try {
            wrapper.eq(ObjectUtil.isNotEmpty(qo.getWid()) && qo.getWid() != 0, "window_id", qo.getWid())
                    .eq("state", ShopGoods.GOODS_UP)
                    .eq("is_del", ShopGoods.DELETE_NO)
                    .like(StringUtils.hasText(qo.getKeyword()), "goods_name", qo.getKeyword())
                    .orderByDesc(GoodsQuery.SORT_SALES == qo.getType(), "sale_num")
                    .orderByAsc(GoodsQuery.SORT_PRICE == qo.getType(), "goods_price");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.page(shopGoodsPage, wrapper);
    }


    @Override
    public ShopGoods getGoodsById(Long id) {
        // 查询菜品的图片列表
        QueryWrapper<ShopGoodsImage> imageQueryWrapper = new QueryWrapper<>();
        imageQueryWrapper.eq("goods_id", id).orderByDesc("sort");
        List<ShopGoodsImage> imageList = goodsImageMapper.selectList(imageQueryWrapper);
        // 查询菜品的属性列表
        QueryWrapper<ShopGoodsAttr> attrQueryWrapper = new QueryWrapper<>();
        List<ShopGoodsAttr> attrList = goodsAttrMapper.selectList(attrQueryWrapper.eq("goods_id", id));
        // 查询菜品详情
        ShopGoods shopGoods = super.getById(id);
        shopGoods.setImageList(imageList);
        shopGoods.setAttrList(attrList);
        return shopGoods;
    }

    @Override
    public List<ShopGoods> queryHotGoods() {
        QueryWrapper<ShopGoods> wrapper = new QueryWrapper<>();
        wrapper.eq("state", ShopGoods.GOODS_UP)
                .eq("is_del", ShopGoods.DELETE_NO)
                .eq("is_hot", ShopGoods.IS_HOT);
        return super.list(wrapper);
    }
}
